//
//  ClockViewController.m
//  FitTime
//
//  Created by 赵建平 on 16/3/30.
//  Copyright © 2016年 赵建平. All rights reserved.
//

#import "ClockViewController.h"
#import "AddTimeViewController.h"
#import "TimePlanTableViewCell.h"


@interface ClockViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *timeView; //表盘

@property (nonatomic, strong) UILabel *day;

@property (nonatomic, strong) UILabel *time;

@property (nonatomic, strong) UILabel *weekDay;

@property (nonatomic, strong) NSMutableArray *timeDataSource;

@property (nonatomic, strong) MulticolorView *colorView; // 五色圆

@property (nonatomic, strong) CoreDataManager *coreDataManager;

@property (nonatomic, assign) NSInteger isFirst;
@end

@implementation ClockViewController

- (void)viewWillAppear:(BOOL)animated {
   
    [_colorView startAnimation];
    [self timeAction];
    [self selectData];
   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.timeDataSource = [NSMutableArray arrayWithCapacity:0];
    
    self.coreDataManager = [CoreDataManager shareCoreDataManager];
    
    [self timeAction];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView *backImageView = [[UIImageView alloc] initWithFrame:self.view.frame];
    
    [self.view addSubview:backImageView];
    
    backImageView.image = [UIImage imageNamed:@"闹钟壁纸.png"];
    backImageView.contentMode = UIViewContentModeScaleAspectFill;
    
    self.timeView = [UIView new];
    [self.view addSubview:self.timeView];
    
    [self.timeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY).offset(-60 * SCALEHEIGHT);
        make.size.mas_equalTo(CGSizeMake(250 * SCALEHEIGHT, 250 * SCALEHEIGHT));
    }];
    
    //设置圆角
    [_timeView.layer setCornerRadius:250 * SCALEHEIGHT / 2];
    _timeView.layer.masksToBounds = YES;
    _timeView.layer.borderWidth = 2 * SCALEHEIGHT;
    _timeView.layer.borderColor = [[UIColor colorWithRed:1.000 green:1.000 blue:0.400 alpha:1.000] CGColor];
    // 五色圆
    self.colorView = [[MulticolorView alloc] initWithFrame:CGRectMake(0, 0, 340 * SCALEHEIGHT, 340 * SCALEHEIGHT)];
    _colorView.center = CGPointMake(self.view.center.x, self.view.center.y - 60 * SCALEHEIGHT);
    [_colorView startAnimation];
    [self.view addSubview:_colorView];
    // 摇摆小球
       PendulumView *pendulum = [[PendulumView alloc] initWithFrame:CGRectMake(0, 20, SCREENWIDTH * SCALEWIDTH, 80 * SCALEHEIGHT) ballImage:@"小球蓝.png" ballDiameter:16 * SCALEHEIGHT];
    pendulum.center = CGPointMake(self.view.center.x, 100 * SCALEWIDTH);
    [self.view addSubview:pendulum];
    
    self.time = [UILabel new];
    _time.textAlignment = NSTextAlignmentCenter;
    [_timeView addSubview:_time];
    
    [_time mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_timeView.mas_top).offset(65 * SCALEHEIGHT);
        make.centerX.equalTo(_timeView.mas_centerX);
        make.height.equalTo(@50);
        make.left.equalTo(@10);
        make.right.equalTo(@-10);
    }];
    
    self.day = [UILabel new];
    _day.textAlignment = NSTextAlignmentCenter;
    [_timeView addSubview:_day];
    
    
    [_day mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_time.mas_top).offset(50 * SCALEWIDTH);
        make.centerX.equalTo(_timeView.mas_centerX);
        make.height.equalTo(@50);
        make.left.equalTo(@20);
        make.right.equalTo(@-20);
    }];
    
    
    self.weekDay = [UILabel new];
    _weekDay.textAlignment = NSTextAlignmentCenter;
    [_timeView addSubview:_weekDay];
    
    [_weekDay mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_day.mas_top).offset(45 * SCALEWIDTH);
        make.centerX.equalTo(_timeView.mas_centerX);
        make.height.equalTo(@50);
        make.left.equalTo(@20);
        make.right.equalTo(@-20);
    }];
    
    [self creatTableView];
    
    [self selectData];
    
    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"➕⏰" style:UIBarButtonItemStylePlain target:self action:@selector(rightAction:)];
    
}

- (void)timeAction {
    
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatterDay = [[NSDateFormatter alloc] init];
    [dateFormatterDay setDateFormat:@"YYYY-MM-dd"];
    NSString *Day = [dateFormatterDay stringFromDate:currentDate];
    // 12小时
    //    NSDateFormatter *dateFormatterTime = [[NSDateFormatter alloc] init];
    //    [dateFormatterTime setDateFormat:@"hh:mm:ss"];
    //    NSString *Time = [dateFormatterTime stringFromDate:currentDate];
    
    // 24小时
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init] ;
    NSInteger unitFlags = NSCalendarUnitWeekday | NSCalendarUnitHour |
    NSCalendarUnitMinute |
    NSCalendarUnitSecond;
    
    comps = [cal components:unitFlags fromDate:currentDate];
    
    NSInteger week = comps.weekday;
    NSString *hour = [NSString stringWithFormat:@"%ld", comps.hour];
    NSString *minute = [NSString stringWithFormat:@"%ld", comps.minute];
    NSString *second = [NSString stringWithFormat:@"%ld", comps.second];
    
    NSArray *arrWeek = @[@"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六"];
    
    // 切换12小时24小时
    //    _time.text = Time;
    if (comps.hour < 10) {
        hour = [NSString stringWithFormat:@"0%ld", comps.hour];
    }
    if (comps.minute < 10) {
        minute = [NSString stringWithFormat:@"0%ld", comps.minute];
    }
    if (comps.second < 10) {
        second = [NSString stringWithFormat:@"0%ld", comps.second];
    }
    _time.text = [NSString stringWithFormat:@"%@:%@:%@", hour, minute, second];
    _time.textColor = [UIColor colorWithWhite:0.098 alpha:1.000];
    _time.font = [UIFont fontWithName:@"Digital-7" size:60 * SCALEHEIGHT];
    
    _day.text = Day;
    _day.textColor = [UIColor colorWithWhite:0.298 alpha:1.000];
    _day.font = [UIFont fontWithName:@"Digital-7" size:35 * SCALEHEIGHT];
    
    _weekDay.text = [NSString stringWithFormat:@"%@", [arrWeek objectAtIndex:week - 1]];
    _weekDay.textColor = [UIColor blackColor];
    _weekDay.font = [UIFont systemFontOfSize:28 * SCALEHEIGHT weight:2];
    
}

#pragma mark selectData 
- (void)selectData {
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"TImes" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"%@", error);
    }else{

        self.timeDataSource = [NSMutableArray arrayWithArray:fetchedObjects];
    }
    
    [self.tableView reloadData];
        
}

#pragma mark TableViewCreat
- (void)creatTableView {
    
        self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [self.view addSubview:self.tableView];
        
        self.tableView.showsVerticalScrollIndicator = NO;
        self.tableView.backgroundColor = [UIColor clearColor];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@20);
            make.right.equalTo(@-20);
            make.height.offset(160 * SCALEHEIGHT);
            make.bottom.equalTo(@-69);
        }];
//    [self.tableView registerClass:[TimePlanTableViewCell class] forCellReuseIdentifier:@"Cell"];
    
}

#pragma mark
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TImes *timer = self.timeDataSource[indexPath.row];
    
    NSString *time = [NSString stringWithFormat:@"%@-%@-%@", timer.hour, timer.minute, timer.week];
    
    if (timer.week.length == 21) {
        UIApplication *app = [UIApplication sharedApplication];
        NSArray *myArray = [app scheduledLocalNotifications];
        
        for (int i = 0; i < myArray.count; i++) {
            UILocalNotification * myUILocalNotification=[myArray objectAtIndex:i];
            
            if ([[[myUILocalNotification userInfo] objectForKey:time] isEqualToString:[NSString stringWithFormat:@"%@-%@", time, timer.musicName]]) {
                [[UIApplication sharedApplication] cancelLocalNotification:myUILocalNotification];
           
            }
            
        }
        
    } else {
        UIApplication *app = [UIApplication sharedApplication];
        NSArray *myArray = [app scheduledLocalNotifications];
        
        for (int i = 0; i < timer.week.length / 3; i++) {
            NSString *string = [timer.week substringWithRange:NSMakeRange(i * 3, 3)];
            for (int j = 0; j < myArray.count; j++) {
                UILocalNotification * myUILocalNotification=[myArray objectAtIndex:j];
                
                if ([[[myUILocalNotification userInfo] objectForKey:[NSString stringWithFormat:@"%@-%@", timer.week, string]] isEqualToString:[NSString stringWithFormat:@"%@-%@-%@", time, string, timer.musicName]]) {
                    [[UIApplication sharedApplication] cancelLocalNotification:myUILocalNotification];
                }
                
            }
            
        }
        
    }
    
    [self.coreDataManager.managedObjectContext deleteObject:timer];
    
    [self.coreDataManager saveContext];
    
    [self.timeDataSource removeObjectAtIndex:indexPath.row];
    
    [self.tableView reloadData];
}

#pragma marl TableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.timeDataSource.count;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger cellHeight = 80;
    return cellHeight * SCALEHEIGHT;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TimePlanTableViewCell *cell = [[TimePlanTableViewCell alloc] init];
    
    cell.timer = self.timeDataSource[indexPath.row];
    
    cell.backgroundColor = [UIColor clearColor];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
    
}



- (void)rightAction:(id)sender {
    
    if (self.timeDataSource.count < 10) {
        
        AddTimeViewController *addTimeVC = [[AddTimeViewController alloc] init];
        
        addTimeVC.todayWeek = _weekDay.text;
        
        [self.navigationController pushViewController:addTimeVC animated:YES];
        
        self.navigationController.navigationBarHidden = YES;
        
        self.navigationController.tabBarController.tabBar.hidden = YES;

    } else {
        
        UIAlertView *alartView = [[UIAlertView alloc]initWithTitle:nil message:@"闹钟太多有害身体健康😊" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alartView show];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
